package com.ebeitech.doorapp.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.constants.ActionConstants;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.util.FileUtil;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.view.StatusBarCompat;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.LOG;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by alice on 2017/11/1.
 */
public class CordovaBaseActivity extends CordovaActivity {

	private Context mContext;
	@BindView(R.id.webView)
	SystemWebView webView;
	@BindView(R.id.titleBar)
	CommonTitleBar mTitleBar;
	private CordovaWebView mCordovaWebView;

	private String url;
	private boolean isNeedTitle;
	private boolean isFitStatusBar = true;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		savedInstanceState.putBoolean(SPConstants.IS_FIT_STATUS_BAR, false);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_cordova);

		isFitStatusBar = StatusBarCompat.setStatusBar(this, null);
		if (isFitStatusBar) {
			StatusBarCompat.compat(this);
		}

		ButterKnife.bind(this);
		super.init();
		mContext = this;
		initView();
		registerBroadCast();

		Intent intent = getIntent();
		if (intent != null) {
			url = intent.getStringExtra("url");
			isNeedTitle = intent.getBooleanExtra("isNeedTitle", false);
		}
		if (!StringUtil.isStringNullOrEmpty(url)) {
			loadUrl(url);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (isFitStatusBar) {
			StatusBarCompat.fitsSystemWindows(this);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ActionConstants.ACTION_EXIT_APP);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (ActionConstants.ACTION_EXIT_APP.equals(action)) {
				finish();
			}
		}
	};

	private void loadJS(String jsName) {
		// 通知APP
		try {
			byte[] bytes = FileUtil.readInputStream(getResources().getAssets().open("www/js/" + jsName + ".js"));
			loadUrl("javascript:" + new String(bytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initView() {
		setNavigationBarHidden(!isNeedTitle);
		webView.setWebViewClient(new SystemWebViewClient((SystemWebViewEngine) mCordovaWebView.getEngine()) {
			@Override
			public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
				try {
					String scheme = "ebeiapp";
					if ((scheme + "://cordova.js").equals(url.toLowerCase())) {
						return new WebResourceResponse("text/javascript", "UTF-8",
								mContext.getAssets().open("www/cordova.js"));
					} else if ((scheme + "://cordova_plugins.js").equals(url.toLowerCase())) {
						return new WebResourceResponse("text/javascript", "UTF-8",
								mContext.getAssets().open("www/cordova_plugins.js"));
					} else if ((scheme + "://sqliteplugin.js").equals(url.toLowerCase())) {
						return new WebResourceResponse("text/javascript", "utf-8",
								mContext.getAssets().open("www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js"));
					} else if ((scheme + "://ebeiplugins.js").equals(url.toLowerCase())) {
						return new WebResourceResponse("text/javascript", "UTF-8",
								mContext.getAssets().open("www/plugins/cordova-plugin-common/www/EbeiPlugins.js"));
					} else if (url.toLowerCase().contains(PublicUtil.getCordovaFilePrefix(mContext))) {
						if (url.length() == PublicUtil.getCordovaFilePrefix(mContext).length()) {
							return null;
						}
						String str1 = url.substring(PublicUtil.getCordovaFilePrefix(mContext).length());
						if (!str1.startsWith("/")) {
							str1 = "/" + str1;
						}
						str1 = PublicUtil.getAppFile(mContext) + str1;
						return new WebResourceResponse("text/plain", "UTF-8",
								new FileInputStream(str1));
					} else if (url.toLowerCase().contains((scheme + "://"))) {
						String str1 = "www/" + url.substring(3 + url.lastIndexOf(":"));
						return new WebResourceResponse("text/javascript", "UTF-8",
								mContext.getAssets().open(str1));
					}

					return super.shouldInterceptRequest(view, url);
				} catch (IOException e) {
					if (!(e instanceof FileNotFoundException)) {
						LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e);
					}
					// Results in a 404.
					return new WebResourceResponse("text/plain", "UTF-8", null);
				}
			}
		});
	}

	@Override
	protected CordovaWebView makeWebView() {
		mCordovaWebView = new CordovaWebViewImpl(new SystemWebViewEngine(webView));
		return mCordovaWebView;
	}

	@Override
	protected void createViews() {
		if (preferences.contains("BackgroundColor")) {
			int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
			// Background of activity:
			appView.getView().setBackgroundColor(backgroundColor);
		}

		appView.getView().requestFocusFromTouch();
	}

	public void setNavigationBarHidden(boolean isHidden) {
		if (isHidden) {
			mTitleBar.setVisibility(View.GONE);
		} else {
			mTitleBar.setVisibility(View.VISIBLE);
		}
	}

}
